package io.mqttpush.mqttserver.handles;

import io.mqttpush.mqttserver.config.TopicManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;

import java.util.List;

/**
 * @author tianzhenjiu
 * @date 2020/4/27 16:22
 */
public class SubscribeService  implements Iservice<MqttSubscribeMessage>{

    @Override
    public boolean accept(ChannelHandlerContext context, MqttMessage inMessage) {

        return MqttMessageType.SUBSCRIBE==inMessage.fixedHeader().messageType();
    }

    @Override
    public List<Object> service(ChannelHandlerContext context, List<Object> outMessage, MqttSubscribeMessage inMessage) {
        outMessage.add( processSubscribe(context.channel(),inMessage));

        return outMessage;
    }


    /**
     * 订阅操作 向服务器订阅所有感兴趣的主题 并且按照客户端标识找到未读消息接受这些消息
     *
     * @param channel
     * @param subscribeMessage
     */
    private MqttSubAckMessage processSubscribe(final Channel channel, MqttSubscribeMessage subscribeMessage) {



        List<MqttTopicSubscription> list = subscribeMessage.payload().topicSubscriptions();
        int[] qoslevels = new int[list.size()];
        if (qoslevels.length <= 0) {
            return null;
        }

        int i = 0;
        for (MqttTopicSubscription subscription : list) {
            qoslevels[i] = subscription.qualityOfService().value();
            String topicName=subscription.topicName();
            TopicManager.getInstance().subscribe(topicName,channel, subscription.qualityOfService());

        }



        MqttQoS mqttQoS = subscribeMessage.fixedHeader().qosLevel();
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBACK, false, mqttQoS, false, 0);
        MqttSubAckPayload payload = new MqttSubAckPayload(qoslevels);
        MqttMessageIdVariableHeader mqttMessageIdVariableHeader = MqttMessageIdVariableHeader
                .from(subscribeMessage.variableHeader().messageId());
        MqttSubAckMessage subAckMessage = new MqttSubAckMessage(fixedHeader, mqttMessageIdVariableHeader, payload);

        return subAckMessage;

    }
}
